package stack;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 155.最小栈
 * 设计一个支持 push ，pop ，top 操作，并能在常数时间内检索到最小元素的栈。
 * 实现 MinStack 类:
 * ● MinStack() 初始化堆栈对象。
 * ● void push(int val) 将元素val推入堆栈。
 * ● void pop() 删除堆栈顶部的元素。
 * ● int top() 获取堆栈顶部的元素。
 * ● int getMin() 获取堆栈中的最小元素。
 */

/**
 * hot100一刷
 */
public class MinStack {
    private Deque<Integer> stack;
    private Deque<Integer> minStack;

    public MinStack() {
        stack = new LinkedList<>();
        minStack = new LinkedList<>();
    }

    public void push(int val) {
        stack.push(val);
        if (minStack.isEmpty() || val <= minStack.peek()) {
            minStack.push(val);
        } else {
            Deque<Integer> temp = new LinkedList<>();
            while (!minStack.isEmpty() && val > minStack.peek()) {
                temp.push(minStack.pop());
            }
            minStack.push(val);
            while (!temp.isEmpty()) {
                minStack.push(temp.pop());
            }
        }
    }

    public void pop() {
        int target = stack.pop();
        Deque<Integer> temp = new LinkedList<>();
        while (!minStack.isEmpty()) {
            int pop = minStack.pop();
            if (pop == target) {
                break;
            }
            temp.push(pop);
        }
        while (!temp.isEmpty()) {
            minStack.push(temp.pop());
        }
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }

    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(512);
        minStack.push(-1024);
        minStack.push(-1024);
        minStack.push(512);
        minStack.pop();
        minStack.getMin();
        minStack.pop();
        minStack.getMin();
        minStack.pop();
        minStack.getMin();
    }
}

/**
 * hot100二刷
 */
class s {

    private Deque<Integer> q;
    private Deque<Integer> min;

    public s() {
        q = new LinkedList<>();
        min = new LinkedList<>();
    }

    public void push(int val) {
        q.push(val);
        if (min.isEmpty()) {
            min.push(val);
        } else {
            min.push(min.peek() < val ? min.peek() : val);
        }
    }

    public void pop() {
        q.pop();
        min.pop();
    }

    public int top() {
        return q.peek();
    }

    public int getMin() {
        return min.peek();
    }
}
